package com.tianyu.service.tcp;


import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;


/**********************************
 * @Author YSW
 * @Description
 * @Date 2020.12.16 - 10:01
 **********************************/

@Slf4j
public class TcpClientChannelHandler extends SimpleChannelInboundHandler<byte[]> {

    private final TianyuCompanyMessage message;

    public TcpClientChannelHandler(TianyuCompanyMessage message) {
        this.message = message;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, byte[] bytes) throws Exception {
        try {
            switch (bytes[0] & 0xFF) {
                case 0x01 -> {
                    if (bytes[1] == 0x01) {
                        log.info("项目[{}] 云平台TCP 注册成功!", message.getCompanyId());
                    }
                }
                case 0x02 -> {
                    log.debug("项目[{}] 云平台 心跳...", message.getCompanyId());
                }
                case 0x0A -> {
                    final byte[] jsonBytes = new byte[bytes.length - 2];
                    System.arraycopy(bytes, 2, jsonBytes, 0, jsonBytes.length);
                    final String taskStr = new String(jsonBytes);
                    if (bytes[1] == 0x01) {
                        log.info("开始任务 - " + taskStr);
                    }
                    if (bytes[1] == 0x00) {
                        log.info("结束任务 - " + taskStr);
                        log.info("结束任务！");
                    }
                }
                case 0xA9 -> {

                }
                default -> {
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.debug("Tcp读取数据异常！");
        }
    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ByteBuf buffer = Unpooled.buffer();
        buffer.writeByte(0x01);
        buffer.writeInt(message.getCompanyId());
        buffer.writeBytes(message.getToken().getBytes());
        byte[] bytes = new byte[buffer.readableBytes()];
        buffer.readBytes(bytes);
        ctx.channel().writeAndFlush(bytes);
        buffer.release();
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleState state = ((IdleStateEvent) evt).state();
            if (state == IdleState.WRITER_IDLE) {
                ByteBuf buffer = Unpooled.buffer();
                buffer.writeByte(0x02);
                buffer.writeLong(System.currentTimeMillis());
                byte[] bytes = new byte[buffer.readableBytes()];
                buffer.readBytes(bytes);
                ctx.channel().writeAndFlush(bytes);
                buffer.release();
            }
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("项目[" + message.getCompanyId() + "] 云平台断开连接");

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.channel().close();
    }
}